<template>
  <el-form>
    <el-form-item>
      <el-row v-for="(port, index) of ports" :key="index" class="portRow">
        <el-row :gutter="10" style="margin-bottom: 3px;">
          <el-col :span="4">名称</el-col>
          <el-col :span="16">
            <el-input v-model="port.name"></el-input>
          </el-col>
          <el-col :span="4">
            <el-button icon="el-icon-plus" type="primary" circle @click="handleAddPort"></el-button>
          </el-col>
        </el-row>
      
        <el-row :gutter="10">
          <el-col :span="4">位置</el-col>
          <el-col :span="16">
            <el-select v-model="port.position" style="width: 100%;">
              <el-option v-for="position of positionOptions" :key="position.value" 
              :label="position.label" :value="position.value"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button icon="el-icon-minus" type="danger" circle @click="handleDeletePort(index)"></el-button>
          </el-col>
        </el-row>
      </el-row>
    </el-form-item>
  </el-form>
</template>

<script>
var _ = require('lodash')
import ConfigUtil from '@/utils/graph-utils/configUtil'

export default {
  name: 'PortPanel',
  data() {
    return {
      ports: [{
        name: '',
        position: ''
      }]
    }
  },
  computed: {
    positionOptions() {
      return ConfigUtil.getPortPositionOptions()
    }
  },
  methods: {
    handleAddPort() {
      this.ports.push({
        name: '',
        position: ''
      })
    },

    handleDeletePort(index) {
      this.ports.splice(index, 1)
    },

    setPortInfo(value) {
      this.ports = []
      if (value && value.items) {
        for (const item of value.items) {
          const name = item.group
          const position = value.groups[name].position
          this.ports.push({
            name: name,
            position: position
          })
        }
      }

      if (this.ports.length === 0) {
        this.ports.push({
          name: '',
          position: ''
        })
      }
    },

    getPortInfo() {
      const portInfo = {
        groups: {},
        items: []
      }
      const portAttr = {
        circle: {
          r: 3,
          magnet: true,
          stroke: '#5F95FF',
          strokeWidth: 1,
          fill: '#ffffff',
          style: {
            visibility: 'hidden'
          }
        }
      }

      for (const port of this.ports) {
        if (port.name === '' || port.position === '') {
          continue
        }

        const path = 'groups.' + port.name
        _.set(portInfo, path, {
          position: port.position,
          attrs: portAttr
        })
        portInfo.items.push({
          group: port.name
        })
      }
      return portInfo.items.length > 0 ? portInfo : null
    }
  }
}
</script>

<style scoped>
.portRow {
  border: 1px solid #b7b7b7; 
  padding: 5px;
  margin-bottom: 2px;
}
</style>